<?php defined('SMIT_PATH') or die('Access Denied');
/**
 *	handlers/user.php - user functions handler
 *	This is Smit Matterhorn - Build 24109
 *	TODO: Move the Core, Abstraction layer
 *	
 *
 * @author		The SmitBoard Team & Community
 * @license		GNU GPL v3
 * @link		http://smitboard.sf.net
 * @since		Matterhorn
 */
 
class UserHandler
{
	public $base;
	public $db;

	public function __construct()
	{
		$this->base = SmitBase::getInstance();
		$this->db = &$this->base->db;
	}

	public function authenticate($username, $password)
	{
		$this->db->select('key')->from('users')->where('username', $username)->run();
		if($this->db->num_rows() > 0)
		{
			$user = $this->db->row();
			$conditions = array(
				'username' => $username,
				'password' => $this->base->lib->user_hash($password, $user['key'])
			);
			$this->db->select('id')->from('users')->where($conditions)->run();
			// It Should be one result, right? or something is wrong!
			if($this->db->num_rows() == 1)
			{
				return TRUE;
			}
		}
		return FALSE;
	}

	public function get_id_by_username($username)
	{
		$this->db->select('id')->from('users')->where('username', $username)->run();
		if($this->db->num_rows() > 0)
		{
			return $this->db->row('id');
		}
		return FALSE;
	}

	public function create($username, $password, $email, $nickname = NULL, $gender = -1)
	{
		if($nickname == NULL)
		{
			$nickname = $username;
		}
		if($gender == NULL)
		{
			$gender = -1;
		}
		$this->db->select('id')->from('users')->where('username', $username)->run();
		if($this->db->num_rows() == 0)
		{
			$this->db->select('id')->from('users')->where('email', $email)->run();
			if($this->db->num_rows() == 0)
			{
				$this->db->select('id')->from('users')->where('nickname', $nickname)->run();
				if($this->db->num_rows() == 0)
				{
					$fields = array(
						'gid' => 3,
						'username' => $username,
						'password' => $this->base->lib->user_hash($password),
						'key' => LATEST_SALT,
						'activation_key' => str_shuffle(time()),
						'join_date' => $this->base->lib->timestamp(),
						'email' => $email,
						'nickname' => $nickname,
						'gender' => $gender
					);
					$this->base->db->insert('users', $fields);
				}
				else
				{
					return 'E_TAKEN_NICKNAME';
				}
			}
			else
			{
				return 'E_TAKEN_EMAIL';
			}
		}
		else
		{
			return 'E_TAKEN_USERNAME';
		}
	}
}
?>